from django.db import models
import math
import hashlib
from pypinyin import lazy_pinyin
from markdown import markdown
# Create your models here.


class User(models.Model):
    # 大家在hdudb使用真实名称……还是别吧
    name = models.CharField(max_length=25, primary_key=True, default="NULL")
    token = models.CharField(max_length=64)  # 存储用户名与密码连起来的sha-256哈希值

    def __str__(self):
        return self.name

    @staticmethod
    def get_foo():
        return User.objects.get(pk="NULL")


class Lesson(models.Model):
    name = models.CharField(max_length=200)  # 课程名称
    teacher = models.CharField(max_length=100)  # 老师名字
    date = models.DateField(auto_now_add=True)  # 添加日期
    credit = models.FloatField()  # 学分
    appraisal_method = models.CharField(max_length=100, default='NULL')  # 考核方式
    course_type = models.CharField(max_length=50, default='NULL')  # 课程性质
    period_start = models.IntegerField(default=-1)  # 课程开始的周
    period_end = models.IntegerField(default=-1)  # 课程结束的周
    course_offering_institute = models.CharField(
        max_length=50, default='NULL')  # 开课学院
    offering_class_now = models.BooleanField(default=True)  # 是否开课
    protected = models.BooleanField(default=False)
    # 平均得分

    def avgscore(self):
        if self.student_set.all():
            students = self.student_set.all()
            sum = 0  # 总得分
            people = 0  # 有效人数
            for student in students:
                if(student.score != -1):
                    sum += student.score
                    people += 1
            if people != 0:
                return sum/people
            else:
                return -1
        else:
            return -1

    # 平均打分
    def avgrate(self):
        students = self.student_set.all()
        if(students):
            sumrate = 0.0
            for student in students:
                sumrate += student.rate
            return math.floor(sumrate/len(students))
        else:
            return -1  # 如果这个课程还没人打过分，返回-1以标记

    def name2pinyin(self):
        return ''.join(lazy_pinyin(self.teacher))

    def offer_class_status(self):
        if(self.offering_class_now):
            return "是"
        else:
            return "否"

    def bestcomment(self):
        max_likes = -1  # 所有喜欢数都比 -1 大
        if self.comment_set.all():
            for comment in self.comment_set.all():
                if comment.likes > max_likes:
                    max_likes = comment.likes
                    id = comment.id
            comment = Comment.objects.get(pk=id)
            if(len(comment.comment) <= 50):
                return comment
            else:
                comment.comment = comment.comment[:50] + '...'
                return comment
        else:
            return Comment(user = User.get_foo(), comment="暂时没有评论💔")

    def __str__(self):
        return self.name+" "+self.teacher


class Comment(models.Model):
    model = models.ForeignKey(Lesson, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.DO_NOTHING, default=User.get_foo)
    score = models.FloatField(default=-1)  # 得分（满分100），用-1标识没有填写
    title = models.CharField(max_length=100, default="无标题")
    comment = models.CharField(max_length=2000)  # 对课程的评论
    # 学期，比如2020-2 2020年第二学期（但实际上在2021年3月开学。这个默认值的意思是杭电（至少官方这么说）在1956年成立
    term = models.CharField(max_length=6, default="1956-1")
    likes = models.IntegerField(default=0)
    # 打分，十分制，因为五星会导致打分过于集中——你会很轻松地打出五星好评，但是10/10就得掂量一下了。
    rate = models.IntegerField(default=10)
    date = models.DateField(auto_now_add=True)  # 添加日期
    protected = models.BooleanField(default=False)

    def likeit(self):
        self.likes += 1
        self.save()
        return self.likes

    def __str__(self):
        return self.comment[:20]

    def html(self):
        return markdown(self.comment)